<?php
namespace App\Controllers\Order;
use App\Models\Order\OrderCommentPra;
use App\Models\Order\OrderComment;

/**
*	设置商品评介点赞
*/
class SetOrderCommonPra extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }
	
	public function execute(){
		$user = $this->session->user;
		//获取信息
		$praiseId = $this->request->get('praiseId');//评价id
		//验证
		if( empty( $praiseId ) ){
			return \App\Libs\Views\Json::view(1, '评价不存在', Null );
		}
		
		//是否有当前评论
		$orderCommentInfo = OrderComment::find(array(
			' id = :ocid: ',
			'bind'=>array( 'ocid' => $praiseId ),
		));
		if( empty( $orderCommentInfo ) ){
			return \App\Libs\Views\Json::view(1, '当前评价不存在', Null );	
		}
		
		//获取是否有评论点赞
		$commonPra = OrderCommentPra::find(array(
			' cid = :cid:  and uid = :uid: ',
			'bind' => array( 'cid'=> $praiseId , 'uid' => $user->id )
		));
		if( empty( $commonPra ) ){
			//没有，添加
			$orderCommonP = new OrderCommentPra();
			$orderCommonP->cid = $praiseId;
			$orderCommonP->uid = $user->id;
			$orderCommonP->show = 1;
			$orderCommonP->ctime = date("Y-m-d H:i:s");
			if( $orderCommonP->save()  == false){
				return  \App\Libs\Views\Json::view(1, '点赞失败', ['show'=>0] );
			}else{
				//添加点赞数
				$orderCommentInfo->zan += 1;
				$orderCommentInfo->save();
				
				return  \App\Libs\Views\Json::view(0, '点赞成功', ['show'=>1] );	
			}
			
		}else{
			//有 修改
			if( $commonPra->show == 1 ){
				$commonPra->show = 2;
			}else{
				$commonPra->show = 1;	
			}
			if( $commonPra->save()  == false){
				return  \App\Libs\Views\Json::view(1, '点赞失败', ['show'=>0] );
			}else{
				if( $commonPra->show == 1 ){
					//添加点赞数
					$orderCommentInfo->zan += 1;
					$orderCommentInfo->save();
				}else{
					//减少点赞数
					$orderCommentInfo->zan -= 1;
					$orderCommentInfo->save();
				}
				return  \App\Libs\Views\Json::view(0, '点赞成功', ['show'=>$commonPra->show] );	
			}
			
		}
		
	}
}
